

import os
import sys
import copy

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, project_root)
# print(project_root)

import asyncio
import logging
from typing import Dict, List, Optional, Callable, Any
import yaml
from src.tools.config_manager import ConfigManager


logger = logging.getLogger(__name__)


class EventAnchor:
    def __init__(self, anchor_config: Dict[str, Any]):
        # 命令事件名
        self.cmd_event = anchor_config.get('event')
        # 模板路径
        self.template_path = str(anchor_config.get('template-path'))
        # 任务模板
        self.config_manager_template = ConfigManager(self.template_path, no_host=True)
        # 锚点列表，转换为list        
        self.anchors = list(anchor_config.get('anchors',[]))

        # print(f"Anchor: {self.cmd_event} template_path: {self.template_path} anchors: ${self.anchors}")


        # 注入参数（需要根据前端数据动态更新）
        self.inject_params = []
        self.anchor_param_map = dict()
    
    
    def inject(self, params: List) :
        self.inject_params = params
        
        # 判断锚点数量和参数数量是否一致
        if len(self.anchors) != len(self.inject_params):
            logger.error(f"Anchor: {self.cmd_event} 锚点数量和参数数量不一致")
            return 
        
        # 建立锚点-参数的映射关系
        for i in range(len(self.anchors)):
            self.anchor_param_map[self.anchors[i]] = self.inject_params[i]

        # 深拷贝一份注入后的配置
        # config_manager_injected = copy.deepcopy(self.config_manager_template)

        for i in range(len(self.config_manager_template.tasks)):
            command = self.config_manager_template.config['tasks'][i]['command']
            for anchor in self.anchors:
                if anchor in command:
                    command = command.replace(anchor, self.anchor_param_map[anchor])
                    self.config_manager_template.tasks[i].command = command
        return self.config_manager_template


class AnchorManager:
    def __init__(self, anchor_register_file: str):
        self.event_anchor_list = dict()
        self.anchor_register_file = anchor_register_file

        self.init_anchors()


    def init_anchors(self):
        self.anchor_configs = self.load_anchor_register(self.anchor_register_file)

        for anchor_config in self.anchor_configs:
                anchor = EventAnchor(anchor_config)
                self.event_anchor_list[anchor.cmd_event] = anchor

    # 载入锚点注册文件
    def load_anchor_register(self, anchor_register_file: str):
        with open(anchor_register_file, 'r') as file:
            return yaml.safe_load(file)
        

    def inject(self, cmd_event: str, params: List):
        event_anchor = self.event_anchor_list[cmd_event]
        if not event_anchor:
            logger.error(f"Anchor: {cmd_event} 未找到对应的事件-锚点类")
            return
        return event_anchor.inject(params)

            








